package com.meiqiang.chat.netty.groupchat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.util.Scanner;

public class GroupChatServer {

    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    private int port;//监听端口

    public GroupChatServer(int port){
        this.port = port;
    }

    //编写run方法，处理客户端请求
    public void run() throws InterruptedException {
        //创建两个线程组
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        ServerBootstrap bootstrap = new ServerBootstrap();
        try {
            bootstrap.group(bossGroup,workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG,128)
                    .childOption(ChannelOption.SO_KEEPALIVE,true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            //向pipeline加入解码器
                            socketChannel.pipeline().addLast("decoder",new StringDecoder());
                            //加入编码器
                            socketChannel.pipeline().addLast("encoder",new StringEncoder());
                            //加入自己的handler
                            socketChannel.pipeline().addLast(new GroupChatServerHandler());
                        }
                    });
            System.out.println("server is start success....");
            ChannelFuture future = bootstrap.bind(port).sync();
            //客户端需要输入信息，加入扫描器
            Scanner scanner = new Scanner(System.in);
            GroupChatServerHandler chatServerHandler = new GroupChatServerHandler();
            while (scanner.hasNextLine()){
                String resMsg =  "【管理员】说:"+scanner.nextLine();
                chatServerHandler.sendToClients(resMsg);
            }
            future.channel().closeFuture().sync();//监听关闭
            System.out.println("========监听关闭");
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }

    public static void main(String[] args) throws InterruptedException {
        new GroupChatServer(7000).run();
    }
}
